﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using myFinance.Domain.LinqToSql;
using myFinance.Domain.Data;

namespace myFinance.Domain {
   public class CategoryRepository : ICategoryRepository  {

       myFinanceData _db;
        public CategoryRepository(myFinanceData data) {            
            _db = data;
            
        }

        /// <summary>
        /// Linq To Sql implementation for Categories
        /// </summary>
        /// <returns>IQueryable of Categories</returns>
        public IQueryable<Category> GetCategories() {

            return from c in _db.DataContext.Categories 
                   select new Category {
                       ID=c.ID,
                       Name=c.Name,
                       Description=c.Description,
                       CategoryType = c.CategoryType
                   };

        }
       /// <summary>
       /// 
       /// </summary>
       /// <param name="category"></param>
        public void Save(Category category) {
            //see if the category is in the system
            myFinance.Domain.LinqToSql.Category dbCategory = GetCategory(category.ID);
            bool isNew = false;
            if (dbCategory == null) {
                dbCategory = new myFinance.Domain.LinqToSql.Category();
                 isNew = true;
            }

            //Assign values to DB Category
            dbCategory.ID = category.ID;
            dbCategory.Name = category.Name;
            dbCategory.Description = category.Description;
            dbCategory.CategoryType = category.CategoryType;

            if (isNew) {
                _db.DataContext.Categories.InsertOnSubmit(dbCategory);
            }
            _db.DataContext.SubmitChanges();
        }

        public Category Read(int id) {
            var category= GetCategory(id);

            return new Category {
                ID = category.ID,
                Name = category.Name,
                Description = category.Description,
                CategoryType = category.CategoryType
            };
        }
        public void Delete(int id) {
            myFinance.Domain.LinqToSql.Category category = GetCategory(id);
            _db.DataContext.Categories.DeleteOnSubmit(category);
            _db.DataContext.SubmitChanges();
        }

        private myFinance.Domain.LinqToSql.Category GetCategory(int id) {
           return  _db.DataContext.Categories.Where(c => c.ID == id).SingleOrDefault();             
        }
    }
}
